<template>
  <div>
    <div :id="id" :style="{ height, padding }" />
  </div>
</template>
<script>
import { Pie } from '@antv/g2plot'

const transformData = [
  { type: '项目数量', value: 22 },
  { type: '待办项目', value: 3 },
  { type: '完成数量', value: 4 }
]
export default {
  props: {
    padding: {
      type: String,
      default: '12px'
    },
    height: {
      type: String,
      default: '120px'
    },

    data: {
      type: Array,
      default: () => [...transformData]
    },
    x: {
      type: String,
      default: 'time'
    },
    y: {
      type: Array,
      default: () => ['value', 'count']
    },
    type: {
      type: String,
      default: 'type'
    }
  },
  data() {
    return {
      dualAxes: null,
      id: (this.$route.name || 'pie') + ((Math.random() * 100000000) | 0)
    }
  },
  watch: {
    data: {
      handler() {
        this.reset()
      },
      deep: true
    }
  },
  mounted() {
    this.renderChart()
    this.$emit('hock:beforeDestroy', () => {
      this.dualAxes.destroy()
    })
  },
  methods: {
    renderChart() {
      this.dualAxes = new Pie(this.id, {
        appendPadding: 0,
        data: this.data,
        angleField: 'value',
        colorField: 'type',
        radius: 1,
        color: ['#6395f9', '#ff4d4f', '#873bf4'],
        innerRadius: 0,
        label: {
          type: 'inner',
          content: '{value}',
          style: {
            textAlign: 'center',
            fontSize: 16
          }
        },
        interactions: [
          { type: 'element-selected' },
          { type: 'element-active' }
        ],
        statistic: {
          title: false,
          content: {
            style: {
              whiteSpace: 'pre-wrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis'
            },
            formatter: () => ''
          }
        }
      })
      this.dualAxes.on('click', k => {
        this.$emit('onClick', k.data)
      })
      this.dualAxes.render()
    },
    reset() {
      this.$nextTick(() => {
        this.dualAxes.options.data = [...this.data]
        this.dualAxes.render()
      })
    }
  }
}
</script>
